from app.models import Solution, DictData
from app import db
from exts import JsonConverter, BeanUtils


def solution_add(solution):
    '''
    添加产品方案
    :param carousel:
    :return:
    '''
    o = JsonConverter.dict_to_object(solution, Solution)
    db.session.add(o)
    db.session.commit()


def solution_update(solution):
    '''
    更新产品方案
    :param carousel:
    :return:
    '''
    '''
    :param news:
    :return:
    '''
    o = Solution.query.get(solution['id'])
    # 对象复制
    BeanUtils.copy(solution, o)
    db.session.commit()


def solution_delete(id):
    '''
    删除产品方案
    :param id:
    :return:
    '''
    o = Solution.query.get(id)
    db.session.delete(o)
    db.session.commit()


def solution_detail(id):
    '''
    查询产品方案详情
    :param id:
    :return:
    '''
    return Solution.query.get(id)


def solution_get_by_id(id):
    '''
    查询产品方案详情
    :param id:
    :return:
    '''
    return Solution.query.get(id)


def solution_page(pageNum, pageSize):
    '''
    分页查询产品方案
    :param params:
    :return:
    '''
    return Solution.query.paginate(page=pageNum, per_page=pageSize)


def solution_all():
    '''
    查询所有产品方案
    :return:
    '''
    return Solution.query.all()


def solution_tree():
    '''
    树形查询
    :return:
    '''
    solution_type_list = DictData.query.filter_by(dict_type='solution_type').all()
    tree = []
    for solution_type in solution_type_list:
        node = {
            'type_code': solution_type.dict_value,
            'type_name': solution_type.dict_label,
            'solutions': []
        }
        solutions = Solution.query.filter_by(solution_type_code=solution_type.dict_value).all()
        for solution in solutions:
            node['solutions'].append({
                'id': solution.id,
                'title': solution.title,
                'image': solution.image,
                'introduce': solution.introduce,
                'create_time': solution.create_time,
                'update_time': solution.update_time
            })
        tree.append(node)

    return tree
